<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小车速度实验分析</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/regression@2.0.1/dist/regression.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .watermark {
            position: fixed;
            bottom: 20px;
            right: 30px;
            opacity: 0.2;
            font-size: 60px;
            color: gray;
            z-index: 9999;
            pointer-events: none;
        }
        
        .header {
            text-align: center;
            font-size: 32px;
            color: #d32f2f;
            margin-bottom: 30px;
            padding: 15px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .input-section {
            flex: 1;
            min-width: 300px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .result-section {
            flex: 2;
            min-width: 500px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        button {
            background-color: #d32f2f;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #b71c1c;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        th {
            background-color: #f2f2f2;
        }
        
        .formula {
            text-align: center;
            margin: 20px 0;
            font-size: 18px;
            font-style: italic;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin-top: 20px;
        }
        
        .conclusion {
            margin-top: 20px;
            padding: 15px;
            background-color: #e8f5e9;
            border-left: 4px solid #4caf50;
            border-radius: 4px;
        }
        
        .instructions {
            background-color: #e3f2fd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #2196f3;
        }
        
        .y-intercept {
            color: #ff5722;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="watermark">百川</div>
    <div class="header">实验：探究小车速度随时间变化的规律</div>
    
    <div class="instructions">
        <h3>使用说明：</h3>
        <ol>
            <li>在下方输入各计数点到起点的距离（单位：米）</li>
            <li>输入相邻计数点之间的时间间隔（单位：0.02秒）</li>
            <li>点击"计算速度"按钮生成结果</li>
            <li>查看数据表格和v-t图像</li>
            <li>可选择是否进行线性拟合（拟合线将延伸到y轴交点）</li>
        </ol>
    </div>
    
    <div class="container">
        <div class="input-section">
            <h2>输入实验数据</h2>
            
            <div class="form-group">
                <label>相邻计数点时间间隔 (单位: 0.02秒):</label>
                <input type="number" id="timeInterval" min="1" value="5">
            </div>
            
            <h3>计数点位置 (米):</h3>
            <div id="pointInputs">
                <!-- 动态生成的输入框 -->
            </div>
            
            <button id="calculateBtn">计算速度</button>
        </div>
        
        <div class="result-section">
            <h2>实验结果</h2>
            
            <div class="formula">
                v = (Δx₂ + Δx₁) / (2T)
            </div>
            
            <div id="resultTable"></div>
            
            <div class="chart-container">
                <canvas id="velocityChart"></canvas>
            </div>
            
            <div>
                <input type="checkbox" id="linearFit" checked>
                <label for="linearFit">显示线性拟合（延伸到y轴）</label>
            </div>
            
            <div id="conclusion" class="conclusion"></div>
        </div>
    </div>

    <script>
        // 初始化计数点输入
        const points = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        const pointInputs = document.getElementById('pointInputs');
        
        points.forEach(point => {
            const div = document.createElement('div');
            div.className = 'form-group';
            div.innerHTML = `
                <label>点 ${point} 的位置 (米):</label>
                <input type="number" step="0.001" id="pos${point}" class="position-input" value="${0.1 * points.indexOf(point)}">
            `;
            pointInputs.appendChild(div);
        });
        
        // 图表变量
        let velocityChart = null;
        
        // 计算按钮点击事件
        document.getElementById('calculateBtn').addEventListener('click', calculateVelocities);
        document.getElementById('linearFit').addEventListener('change', toggleLinearFit);
        
        // 初始计算一次
        setTimeout(calculateVelocities, 500);
        
        function calculateVelocities() {
            // 获取输入数据
            const n = parseInt(document.getElementById('timeInterval').value);
            if (isNaN(n) || n <= 0) {
                alert("请输入有效的时间间隔（正整数）");
                return;
            }
            
            const positions = [];
            let validInput = true;
            
            points.forEach(point => {
                const value = parseFloat(document.getElementById(`pos${point}`).value);
                if (isNaN(value)) {
                    alert(`请输入有效的点 ${point} 位置`);
                    validInput = false;
                    return;
                }
                positions.push(value);
            });
            
            if (!validInput) return;
            
            // 计算时间间隔
            const delta_t = n * 0.02;
            
            // 计算速度
            const velocities = [];
            const time_points = [];
            
            for (let i = 1; i < positions.length - 1; i++) {
                const delta_s = positions[i+1] - positions[i-1];
                const total_time = 2 * delta_t;
                const v = delta_s / total_time;
                velocities.push(v);
                time_points.push(i * delta_t);
            }
            
            // 显示数据表格
            displayDataTable(positions, velocities, points);
            
            // 绘制图表
            drawChart(time_points, velocities);
            
            // 进行线性拟合并显示结论
            performLinearFit(time_points, velocities);
        }
        
        function displayDataTable(positions, velocities, points) {
            let tableHTML = `
                <table>
                    <tr>
                        <th>计数点:</th>
                        ${points.map(p => `<th>${p}</th>`).join('')}
                    </tr>
                    <tr>
                        <th>位置(m):</th>
                        ${positions.map(p => `<td>${p.toFixed(3)}</td>`).join('')}
                    </tr>
                    <tr>
                        <th>速度(m/s):</th>
                        <td>*</td>
                        ${velocities.map(v => `<td>${v.toFixed(3)}</td>`).join('')}
                        <td>*</td>
                    </tr>
                </table>
            `;
            
            document.getElementById('resultTable').innerHTML = tableHTML;
        }
        
        function drawChart(time_points, velocities) {
            const ctx = document.getElementById('velocityChart').getContext('2d');
            
            // 如果已有图表，先销毁
            if (velocityChart) {
                velocityChart.destroy();
            }
            
            // 创建新图表
            velocityChart = new Chart(ctx, {
                type: 'scatter',
                data: {
                    datasets: [{
                        label: '速度数据',
                        data: time_points.map((t, i) => ({x: t, y: velocities[i]})),
                        backgroundColor: 'rgba(54, 162, 235, 0.8)',
                        pointRadius: 8,
                        pointHoverRadius: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '时间 t(s)'
                            },
                            min: 0,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '速度 v(m/s)'
                            },
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: 'v-t 图像',
                            font: {
                                size: 18
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `时间: ${context.parsed.x.toFixed(3)}s, 速度: ${context.parsed.y.toFixed(3)}m/s`;
                                }
                            }
                        }
                    }
                }
            });
            
            // 如果需要，添加线性拟合
            toggleLinearFit();
        }
        
        function performLinearFit(time_points, velocities) {
            if (time_points.length === 0) return;
            
            // 使用回归库进行线性拟合
            const data = time_points.map((t, i) => [t, velocities[i]]);
            const result = regression.linear(data);
            
            const slope = result.equation[0];
            const intercept = result.equation[1];
            const r2 = result.r2;
            
            // 计算y轴交点（t=0时的速度，即初速度）
            const yIntercept = intercept;
            
            // 显示结论
            document.getElementById('conclusion').innerHTML = `
                <h3>分析结果:</h3>
                <p>拟合方程: v = ${slope.toFixed(4)}t + ${intercept.toFixed(4)}</p>
                <p>初速度 v₀ = <span class="y-intercept">${yIntercept.toFixed(4)} m/s</span> (t=0时的速度)</p>
                <p>加速度 a = ${slope.toFixed(4)} m/s²</p>
                <p>通过直接分析图象的特点得到小车运动的v-t图象是一条倾斜的直线，那么当时间增加相同的值Δt时，速度也会增加相同的值Δv。可以得出结论：小车的速度随时间均匀增加（或变化）。</p>
            `;
            
            // 存储拟合结果供图表使用
            window.regressionResult = result;
            
            // 更新图表显示拟合线
            toggleLinearFit();
        }
        
        function toggleLinearFit() {
            if (!velocityChart || !window.regressionResult) return;
            
            const showFit = document.getElementById('linearFit').checked;
            const result = window.regressionResult;
            
            // 添加或移除拟合线数据集
            if (showFit) {
                // 检查是否已存在拟合线
                if (velocityChart.data.datasets.length === 1) {
                    // 生成拟合线上的点 - 延伸到y轴(x=0)
                    const xMin = 0; // 从y轴开始
                    const xMax = Math.max(...velocityChart.data.datasets[0].data.map(d => d.x));
                    
                    const fitData = [
                        {x: xMin, y: result.equation[0] * xMin + result.equation[1]},
                        {x: xMax, y: result.equation[0] * xMax + result.equation[1]}
                    ];
                    
                    velocityChart.data.datasets.push({
                        label: `线性拟合: v = ${result.equation[0].toFixed(4)}t + ${result.equation[1].toFixed(4)}`,
                        data: fitData,
                        backgroundColor: 'rgba(255, 99, 132, 0.8)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        pointRadius: 0,
                        borderWidth: 2,
                        fill: false,
                        showLine: true,
                        type: 'line'
                    });
                }
            } else {
                if (velocityChart.data.datasets.length > 1) {
                    velocityChart.data.datasets.pop();
                }
            }
            
            velocityChart.update();
        }
    </script>
</body>
</html>
